Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(consensus-types): Make slashings use math.Gwei #2038

Merged
merged 5 commits into from
Oct 3, 2024

Conversation

abi87
Copy link
Collaborator

@abi87 abi87 commented Oct 3, 2024

Make Slashings and TotalSlashing share the same type.

Summary by CodeRabbit

  • New Features

    • Updated the representation of slashing amounts in various components to a more specialized type, enhancing clarity and consistency.
  • Bug Fixes

    • Adjusted the handling of slashing amounts across multiple methods to ensure compatibility with the new data type.
  • Refactor

    • Standardized the data types used in interfaces and methods related to slashing, improving overall type safety and maintainability.

Copy link
Contributor

coderabbitai bot commented Oct 3, 2024

Walkthrough

The changes in this pull request primarily focus on updating the BeaconState struct and related interfaces to use math.Gwei instead of uint64 for slashing amounts. This involves altering method signatures and return types across multiple files, ensuring consistency in how slashing data is represented and processed. The modifications affect both the struct definition and various methods, including those for retrieving and setting slashing values, across different components of the codebase.

Changes

File Path Change Summary
mod/consensus-types/pkg/types/state.go Updated Slashings field type from []uint64 to []math.Gwei; modified New method signature.
mod/consensus-types/pkg/types/state_test.go Changed Slashings field type in generateValidBeaconState function from []uint64 to []math.Gwei.
mod/node-api/handlers/proof/merkle/mock/beacon_state.go Altered NewBeaconState function parameter type from []uint64 to []math.Gwei.
mod/node-core/pkg/components/interfaces.go Updated GetSlashings return type to ([]math.Gwei, error); modified New method in BeaconStateMarshallable.
mod/state-transition/pkg/core/state/interfaces.go Changed GetSlashings return type to ([]math.Gwei, error); updated SetSlashingAtIndex method parameter type.
mod/state-transition/pkg/core/state/types.go Updated New method parameter type for slashings from []uint64 to []math.U64.
mod/storage/pkg/beacondb/slashing.go Changed GetSlashings return type to ([]math.Gwei, error); updated internal variable type for slashing.

Possibly related PRs

Suggested labels

Merge me daddy, Ready for Review

Suggested reviewers

  • itsdevbear
  • ocnc

Poem

In the meadow where slashing's delight,
We’ve swapped uints for Gwei, oh what a sight!
With each little change, our code hops with glee,
A beacon of clarity, just wait and see!
So let’s dance through the fields, let our types align,
For a brighter tomorrow, our code will shine! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@abi87 abi87 self-assigned this Oct 3, 2024
@abi87 abi87 changed the title chore(storage): Beacon state inconsistent gwei usage for slashing chore(consensus-types): Make slashings use math.Gwei Oct 3, 2024
Copy link

codecov bot commented Oct 3, 2024

Codecov Report

Attention: Patch coverage is 40.00000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 22.13%. Comparing base (88fe7a0) to head (e4dbb2e).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
mod/storage/pkg/beacondb/slashing.go 0.00% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #2038   +/-   ##
=======================================
  Coverage   22.13%   22.13%           
=======================================
  Files         357      357           
  Lines       16002    16002           
  Branches       12       12           
=======================================
  Hits         3542     3542           
  Misses      12313    12313           
  Partials      147      147           
Files with missing lines Coverage Δ
mod/consensus-types/pkg/types/state.go 64.03% <100.00%> (ø)
...ode-api/handlers/proof/merkle/mock/beacon_state.go 81.39% <100.00%> (ø)
mod/storage/pkg/beacondb/slashing.go 0.00% <0.00%> (ø)

@@ -69,7 +69,7 @@ type BeaconState[
NextWithdrawalValidatorIndex math.ValidatorIndex

// Slashing
Slashings []uint64
Slashings []math.Gwei
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the main point of the PR. Make Slashing and TotalSlashing share the same type

@@ -378,7 +378,7 @@ func (st *BeaconState[
}
subIndx = hh.Index()
for _, i := range st.Slashings {
hh.AppendUint64(i)
hh.AppendUint64(uint64(i))
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: should I use i.Unwrap() here instead? It seems the principled way, but it makes a copy, while casting should not. We do use the uint64 cast for TotalSlashing as well (line 392)

@abi87 abi87 marked this pull request as ready for review October 3, 2024 09:02
Base automatically changed from update-mockery to main October 3, 2024 15:19
An error occurred while trying to automatically change base from update-mockery to main October 3, 2024 15:19
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range comments (1)
mod/storage/pkg/beacondb/slashing.go (1)

Line range hint 32-44: LGTM! Consider pre-allocating the slashings slice for better performance.

The changes to the GetSlashings method align well with the PR objective of using math.Gwei for slashings consistently. The conversion from uint64 to math.Gwei is implemented correctly.

To potentially improve performance, consider pre-allocating the slashings slice if you have an estimate of the number of slashings. This can reduce memory allocations and copies. For example:

-var slashings []math.Gwei
+slashings := make([]math.Gwei, 0, estimatedSlashingsCount)

Replace estimatedSlashingsCount with an appropriate estimate or a constant value based on your use case.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between c1c5172 and f54531f.

📒 Files selected for processing (7)
  • mod/consensus-types/pkg/types/state.go (3 hunks)
  • mod/consensus-types/pkg/types/state_test.go (1 hunks)
  • mod/node-api/handlers/proof/merkle/mock/beacon_state.go (1 hunks)
  • mod/node-core/pkg/components/interfaces.go (2 hunks)
  • mod/state-transition/pkg/core/state/interfaces.go (1 hunks)
  • mod/state-transition/pkg/core/state/types.go (1 hunks)
  • mod/storage/pkg/beacondb/slashing.go (2 hunks)
🔇 Additional comments (13)
mod/storage/pkg/beacondb/slashing.go (2)

Line range hint 50-105: Excellent consistency across slashing-related methods.

The existing methods (GetSlashingAtIndex, SetSlashingAtIndex, GetTotalSlashing, and SetTotalSlashing) already use math.Gwei consistently. This aligns perfectly with the changes made to the GetSlashings method and the overall PR objective.


Line range hint 1-105: Overall excellent implementation and consistency.

The changes made to this file are minimal, focused, and achieve the PR objective of ensuring consistent use of math.Gwei for slashings. The code demonstrates good practices such as:

  1. Consistent use of generics across methods.
  2. Proper error handling.
  3. Clear and concise documentation for each method.

The changes integrate seamlessly with the existing code, maintaining its quality and readability.

mod/node-api/handlers/proof/merkle/mock/beacon_state.go (2)

Line range hint 1-145: Overall assessment of the changes

The modification to use math.Gwei for slashings in the NewBeaconState function is consistent with the PR objective. The change is isolated to a single line and appears to be correct within the context of this file.

However, it's crucial to ensure that this change is consistently applied across the entire codebase, particularly in areas that interact with slashings or expect uint64 slices for this purpose. The verification script provided in the previous comment will help identify any inconsistencies or areas that require further attention.


100-100: Verify the impact of changing slashings type to math.Gwei

The change from []uint64{} to []math.Gwei{} aligns with the PR objective to make slashings use math.Gwei. This modification enhances type consistency for slashings throughout the codebase.

However, we should consider the following:

  1. Ensure that all other parts of the codebase expecting uint64 slices for slashings have been updated accordingly.
  2. Verify that the math.Gwei type has the same or better performance characteristics compared to uint64 for this use case.
  3. Check if this change affects any serialization/deserialization processes, especially if the data is persisted or transmitted.

To ensure consistency across the codebase, please run the following verification script:

This script will help identify any inconsistencies or remaining work related to this change.

mod/state-transition/pkg/core/state/interfaces.go (3)

110-110: Approved: Improved type consistency for slashings

The change from []uint64 to []math.Gwei for the GetSlashings method return type is a positive improvement. It aligns with the PR objective of ensuring Slashings and TotalSlashing share the same data type, enhancing consistency within the codebase. Using math.Gwei also suggests a more precise representation of financial values, which is crucial for slashing calculations.


110-112: Excellent: Achieved full consistency in slashing-related methods

After reviewing the entire interface, it's clear that the changes to GetSlashings and SetSlashingAtIndex have achieved full consistency in the representation of slashing amounts. All slashing-related methods (GetTotalSlashing, SetTotalSlashing, GetSlashings, SetSlashingAtIndex, and GetSlashingAtIndex) now uniformly use math.Gwei. This consistency enhances the interface's clarity and reduces the potential for type-related errors in implementations.


112-112: Approved: Consistent use of math.Gwei for slashing amounts

The change of the amount parameter type from uint64 to math.Gwei in the SetSlashingAtIndex method is approved. This modification maintains consistency with the GetSlashings method and ensures that slashing amounts are uniformly represented using math.Gwei throughout the interface.

To ensure complete consistency, let's verify that all slashing-related methods in the interface use math.Gwei:

✅ Verification successful

Verified: Consistent use of math.Gwei across all slashing-related methods

All slashing-related methods in mod/state-transition/pkg/core/state/interfaces.go consistently use math.Gwei for their parameters and return types. This confirms that the change to SetSlashingAtIndex maintains uniformity throughout the interface.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent use of math.Gwei in slashing-related methods

# Test: Search for methods related to slashing and their types
rg --type go -i '(get|set|total).*slash.*(\w+)' mod/state-transition/pkg/core/state/interfaces.go

Length of output: 593

mod/consensus-types/pkg/types/state_test.go (1)

103-103: Verify test cases with the new math.Gwei type.

While the change shouldn't affect the existing tests, it's crucial to ensure they still pass with the new math.Gwei type for the Slashings field.

Run the following script to verify the tests:

mod/consensus-types/pkg/types/state.go (2)

72-72: LGTM: Type consistency improvement

The change from []uint64 to []math.Gwei for the Slashings field aligns well with the PR objective. This modification enhances type consistency between Slashings and TotalSlashing, improving code clarity and type safety.


100-100: LGTM: Consistent method signature update

The slashings parameter type in the New method has been correctly updated to []math.Gwei, maintaining consistency with the Slashings field type change in the struct. This ensures that the method signature aligns with the updated struct definition.

mod/node-core/pkg/components/interfaces.go (3)

210-210: Type change for slashings parameter

The type of the slashings parameter in the New method of BeaconStateMarshallable interface has been changed from []uint64 to []math.U64. This change aligns with the PR objective of making slashings use math.Gwei.


897-897: Return type change for GetSlashings method

The return type of the GetSlashings method in the BeaconStore interface has been updated from []uint64 to []math.Gwei. This change is consistent with the PR objective and the previous change in the BeaconStateMarshallable interface.


210-210: Summary of changes: Consistent use of math.Gwei for slashings

The changes in this file consistently update the type used for slashings from uint64 to math.Gwei (or math.U64 in one instance). This modification aligns with the PR objective of ensuring that Slashings and TotalSlashing components share the same data type. The changes affect the following interfaces:

  1. BeaconStateMarshallable: Updated slashings parameter type in the New method.
  2. BeaconStore: Updated return type of the GetSlashings method.

These changes enhance type consistency and improve the semantic representation of slashing values in the codebase.

Also applies to: 897-897

@@ -54,7 +54,7 @@ type BeaconStateMarshallable[
randaoMixes []common.Bytes32,
nextWithdrawalIndex uint64,
nextWithdrawalValidatorIndex math.U64,
slashings []uint64, totalSlashing math.U64,
slashings []math.U64, totalSlashing math.U64,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

Inconsistency in the type of slashings across the codebase

After reviewing the occurrences of slashings in the codebase, there is an inconsistency in the types being used:

  • math.U64 in:
    • mod/node-core/pkg/components/interfaces.go
    • mod/state-transition/pkg/core/state/types.go
  • math.Gwei in:
    • mod/storage/pkg/beacondb/slashing.go
    • mod/consensus-types/pkg/types/state.go
  • sdkcollections.Map[uint64, uint64] in:
    • mod/storage/pkg/beacondb/kvstore.go

This inconsistency can lead to confusion and potential type-related issues. It is recommended to standardize the type used for slashings to align with the PR objective of utilizing math.Gwei.

🔗 Analysis chain

Type change improves consistency, but differs from PR objective

The change from []uint64 to []math.U64 for the slashings parameter improves type consistency with totalSlashing. This is a positive change as it likely provides additional functionality or constraints compared to the built-in uint64.

However, there's a discrepancy between the PR objective and the actual change:

  • PR objective: Make slashings use math.Gwei
  • Actual change: Using math.U64

Please clarify if math.U64 is equivalent to math.Gwei or if there's a reason for this difference. If math.Gwei should be used instead, consider updating the type accordingly.

To ensure consistency across the codebase, let's check for other occurrences of slashings and their types:

This will help verify if the type change is consistent with other parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of 'slashings' in Go files
rg --type go 'slashings.*\[?\]?(uint64|math\.U64|math\.Gwei)' -g '!mod/state-transition/pkg/core/state/types.go'

Length of output: 505

@@ -100,7 +100,7 @@ func generateValidBeaconState() *types.BeaconState[
},
Balances: []uint64{32000000000, 31000000000},
RandaoMixes: generateRandomBytes32(65536),
Slashings: []uint64{1000000000, 2000000000},
Slashings: []math.Gwei{1000000000, 2000000000},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

LGTM! Consider updating TotalSlashing for consistency.

The change from []uint64 to []math.Gwei for the Slashings field aligns with the PR objective. This improves type safety and clarity in the code.

However, for consistency, consider updating the TotalSlashing field on line 106 to use math.Gwei as well.

Suggested change for line 106:

-		TotalSlashing:                3000000000,
+		TotalSlashing:                math.Gwei(3000000000),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Slashings: []math.Gwei{1000000000, 2000000000},
Slashings: []math.Gwei{1000000000, 2000000000},
TotalSlashing: math.Gwei(3000000000),

@@ -378,7 +378,7 @@ func (st *BeaconState[
}
subIndx = hh.Index()
for _, i := range st.Slashings {
hh.AppendUint64(i)
hh.AppendUint64(uint64(i))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

LGTM with a suggestion: Consider documenting overflow risk

The casting of math.Gwei to uint64 is consistent with how TotalSlashing is handled and avoids unnecessary copying. However, it's worth considering the following:

  1. Document the assumption that math.Gwei will never exceed the range of uint64.
  2. Consider adding a runtime check to ensure no overflow occurs during the cast.

These steps would help prevent potential issues if math.Gwei's range ever changes in the future.

@abi87 abi87 merged commit 455762b into main Oct 3, 2024
16 checks passed
@abi87 abi87 deleted the beacon-state-inconsistent-gwei-usage branch October 3, 2024 18:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants